package com.example.leepong;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import com.example.leepong.Drawing.DrawingManager;
import com.example.leepong.Game.Engine;
import com.example.leepong.Game.Stage.StageConfiguration;
import com.example.leepong.Game.Utils.PerfsMonitor;
import com.example.leepong.Interaction.GestureHandler;

import java.util.BitSet;

public class GameSurface extends SurfaceView implements SurfaceHolder.Callback {

    private boolean _isInitialized;
    private SurfaceHolder _holder;
    public DrawingManager DrawingManager;
    public Engine Engine;
    private GestureDetector _gestureDetector;
    private GameLoop _gameLoop;
    public StageConfiguration StageConfig;

    public GameSurface(Context context, AttributeSet attrs) {
        super(context, attrs);

        _holder = getHolder();
        _holder.addCallback(this);
        setFocusable(true);
        this.Engine = new Engine();

        _gestureDetector = new GestureDetector(this.getContext(), new GestureHandler(this));
        _gestureDetector.setIsLongpressEnabled(false);

        this.DrawingManager = new DrawingManager(this);
        this.DrawingManager.ShowFps = true;

        _gameLoop = new GameLoop(this);
    }

    public void Initilize(StageConfiguration stageConfig) {
        this.StageConfig = stageConfig;
    }

    public void surfaceCreated(SurfaceHolder iSurfaceHolder) {

        if (!_isInitialized) {
            Engine.Init(getWidth(), getHeight(), this.StageConfig);
            DrawingManager.Init();
            _isInitialized = true;
        }

        if (android.os.Build.VERSION.SDK_INT > 10) {
            Engine.Calibrate(60);
            setWillNotDraw(false);
        } else {
            Engine.Calibrate(45);
            _gameLoop.Launch(45);
        }
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        invalidate();
        Engine.Update();
        DrawingManager.DoDraw(canvas);
    }

    public void surfaceChanged(SurfaceHolder iSurfaceHolder, int int32, int int321, int int322) {
    }

    public void surfaceDestroyed(SurfaceHolder iSurfaceHolder) {
        _gameLoop.Stop();
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        _gestureDetector.onTouchEvent(ev);
        return true;
    }
}


